package com.cizzy.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cizzy.video.common.Result;
import com.cizzy.video.entity.dao.VideoCountDAO;
import com.cizzy.video.mapper.VideoCountMapper;
import com.cizzy.video.service.IVideoCountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author crissy-月下闲人
 * @since 2023-10-29
 */
@Service
public class VideoCountServiceImpl extends ServiceImpl<VideoCountMapper, VideoCountDAO> implements IVideoCountService {
    @Autowired
    private VideoCountMapper videoCountMapper;

    @Override
    public synchronized Result<VideoCountDAO> createVideoCount(VideoCountDAO videoCount) {
        videoCount.setCreateAt(new Timestamp(System.currentTimeMillis()));
        int result = videoCountMapper.insert(videoCount);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("视频计数创建失败");
        }
    }

    @Override
    public synchronized void createVideoCountById(Long videoId) {
        VideoCountDAO videoCount = new VideoCountDAO(videoId);
        int result = videoCountMapper.insert(videoCount);
        if (result > 0) {
            Result.success();
        } else {
            Result.error("视频计数创建失败");
        }
    }

    @Override
    public Result<VideoCountDAO> getVideoCountById(Long id) {
        VideoCountDAO videoCount = videoCountMapper.selectById(id);
        if (videoCount == null) {
            return Result.error("视频不存在");
        } else {
            return Result.success(videoCount);
        }
    }

    @Override
    public synchronized Result<VideoCountDAO> addVideoCountById(String column, Long id, int num) {
        UpdateWrapper<VideoCountDAO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.
                setSql(column + " = " + column + " + " + num).
                eq("video_id", id);
        int result = videoCountMapper.update(null, updateWrapper);
        if (result > 0) {
            return Result.success();
        } else {
            return Result.error("视频计数更新失败");
        }
    }
}
